package com.filldream.fastboot.common.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomUtils;
import java.net.InetAddress;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Stack;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author RickSun && iFillDream
 * @version 1.0
 * @data 2020-10-10 11:34
 * @updata 2023-12-07
 * @description 唯一编号生成器
 */
@Slf4j
public class OrderSnUtil {

    //时区
    private static ZoneId ZONE_ID = ZoneId.of("Asia/Shanghai");
    private static final AtomicInteger SEQ = new AtomicInteger(1000);
    private static final DateTimeFormatter DF_FMT_PREFIX = DateTimeFormatter.ofPattern("yyMMddHHmmssSS");
    private volatile static String IP_SUFFIX = null;
    private static char[] charSet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".toCharArray();

    /**
     * 生成日志编号
     * @return  更简短的编号
     */
    public static String genLogNo(){
        String orderNo = generateOrderNo();
        StringBuilder sb = new StringBuilder();
        sb.append( f10to62(orderNo.substring(0,2),0) ) //年份
                .append( orderNo.substring(2,14) )  //时间
                .append( f10to62(orderNo.substring(15,20),0) );   //尾号
        return sb.toString();
    }

    /**
     * 生成订单号
     * @return
     */
    public static String generateOrderNo(){
        LocalDateTime dataTime = LocalDateTime.now(ZONE_ID);
        if(SEQ.intValue()>9990){
            SEQ.getAndSet(1000);
        }
        return  dataTime.format(DF_FMT_PREFIX)+ getLocalIpSuffix()+SEQ.getAndIncrement();
    }

    /**
     * 获取IP地址
     * @return
     */
    private static String getLocalIpSuffix () {
        if (null != IP_SUFFIX) {
            return IP_SUFFIX;
        }
        try {
            synchronized (OrderSnUtil.class) {
                if (null != IP_SUFFIX) {
                    return IP_SUFFIX;
                }
                InetAddress addr = InetAddress.getLocalHost();
                //  172.17.0.4  172.17.0.199 ,
                String hostAddress = addr.getHostAddress();
                if (null != hostAddress && hostAddress.length() > 4) {
                    String ipSuffix = hostAddress.trim().split("\\.")[3];
                    if (ipSuffix.length() == 2) {
                        IP_SUFFIX = ipSuffix;
                        return IP_SUFFIX;
                    }
                    ipSuffix = "0" + ipSuffix;
                    IP_SUFFIX = ipSuffix.substring(ipSuffix.length() - 2);
                    return IP_SUFFIX;
                }
                IP_SUFFIX = RandomUtils.nextInt(10, 20) + "";
                return IP_SUFFIX;
            }
        } catch (Exception e) {
            log.info("获取IP失败:" + e.getMessage());
            IP_SUFFIX = RandomUtils.nextInt(10, 20) + "";
            return IP_SUFFIX;
        }
    }


    /**
     * 将10进制转化为62进制
     * @param number    数字
     * @param length 转化成的62进制长度，不足length长度的话高位补0，否则不改变什么
     * @return
     */
    public static String f10to62(long number, int length){
        Long rest=number;
        Stack<Character> stack=new Stack<Character>();
        StringBuilder result=new StringBuilder(0);
        while(rest!=0){
            stack.add(charSet[new Long((rest-(rest/62)*62)).intValue()]);
            rest=rest/62;
        }
        for(;!stack.isEmpty();){
            result.append(stack.pop());
        }
        int result_length = result.length();
        StringBuilder temp0 = new StringBuilder();
        if( length > 0 ){
            for(int i = 0; i < length - result_length; i++){
                temp0.append('0');
            }
        }
        return temp0.append( result ).toString();
    }

    /**
     * 将10进制转化为62进制
     * @param number    数字
     * @param length 转化成的62进制长度，不足length长度的话高位补0，否则不改变什么
     * @return
     */
    public static String f10to62(String number, int length){
        return f10to62( Long.valueOf(number),length );
    }

}